﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raven.Client;
using BattleThis.Core;
using Raven.Client.Embedded;
using Raven.Client.Document;
using Raven.Database.Server;

namespace BattleThis.RavenDB
{
	/// <summary>
	/// Factory for Unit of works. Represents the Database.
	/// </summary>
	public class RavenUnitOfWorkFactory : IUnitOfWorkFactory
	{

		#region Variablen
		private static IDocumentStore m_Store;
		private static readonly Object m_LockObject = new Object();
		#endregion

		#region Properties

		/// <summary>
		/// Gets the store aka DB.
		/// </summary>
		public static IDocumentStore Store
		{
			get
			{
				lock( m_LockObject )
				{
					return m_Store;
				}
			}
		}

		#endregion

		#region Methoden

		/// <summary>
		/// Initalizes the specified connection string name.
		/// </summary>
		/// <param name="connectionStringName">Name of the connection string.</param>
		public static void Initalize( string connectionStringName )
		{
			if( string.IsNullOrEmpty( connectionStringName ) )throw new ArgumentNullException( "connectionStringName" );

			m_Store = new EmbeddableDocumentStore { ConnectionStringName = connectionStringName };
			m_Store.Conventions.IdentityPartsSeparator = "-";			
			m_Store.Conventions.ShouldCacheRequest = ( url ) => false;
			m_Store.Conventions.DefaultQueryingConsistency = ConsistencyOptions.QueryYourWrites;

#if DEBUG
			( (EmbeddableDocumentStore)m_Store ).UseEmbeddedHttpServer = true;
#endif

			m_Store.Initialize();
		}

		/// <summary>
		/// Creates a unit of work.
		/// </summary>
		/// <returns></returns>
		public IUnitOfWork Create()
		{
			return new RavenUnitOfWork( Store );
		}

		#endregion
        
	}
}
